package com.marcosnobrega.android.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.marcosnobrega.android.bean.UsersListItem;
import com.marcosnobrega.android.threadservice.PresenceThread;
import com.marcosnobrega.android.threadservice.UpdatePresenceListThread;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings.System;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class UserList extends Activity{
	
	private String myAndroidId;
	private ArrayAdapter<UsersListItem> users;
	private Handler mHandler = new Handler();
	private Runnable mRunnable = new Runnable() {
		
		@Override
		public void run() {
			try {
				loadUsersList();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};
	private Dialog mDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.messageslistlayout);
		this.users = new ArrayAdapter<UsersListItem>(this,R.layout.messageslist);
		this.myAndroidId = System.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
		
		ListView lv = (ListView) findViewById(R.id.usersListView);
		lv.setTextFilterEnabled(true);
		
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				
				Intent intent = new Intent(UserList.this, Conversation.class);
				intent.putExtra("userTo", UserList.this.users.getItem(position));
				UserList.this.startActivity(intent);
			}
			
		});
		
		lv.setAdapter(this.users);
		new Thread(UpdatePresenceListThread.getInstance(mRunnable, mHandler, myAndroidId)).start();
		
	}
	
	private void loadUsersList() throws Exception{
		
		HttpPost request = new HttpPost(AndroidNetwork.SERVICE_URL+"?action="+AndroidNetwork.ACTION_LIST_USERS);
		
		DefaultHttpClient client = new DefaultHttpClient();
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("userAndroidId", myAndroidId));
		
		request.setEntity(new UrlEncodedFormEntity(params));
		
		HttpResponse response = client.execute(request);
		HttpEntity entity = response.getEntity();
		String responseText = EntityUtils.toString(entity);
		this.users.clear();
		if(!responseText.equalsIgnoreCase("")){
			String[] users = responseText.split(";;;");
			for(String s : users){
				String[] userData = s.split(":");
				UsersListItem user = new UsersListItem(userData[0], userData[1]);
				this.users.add(user);
			}
		}
		if(this.users.getCount() == 0){
			this.users.add(new UsersListItem(null, "Caramba! Vai estudar que só tem você online!"));
		}
		
		
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
			case R.id.menu_list_users:
				break;
				
			case R.id.settings:
				break;
				
			case R.id.menu_home:
				break;
				
			case R.id.menu_change_nickname:
				Builder builder = new AlertDialog.Builder(this);
				builder.setIcon(R.drawable.euandroid);
				builder.setTitle(R.string.enternickname);
				EditText nicknameField = new EditText(this);
				nicknameField.setText(R.string.empty);
				nicknameField.setId(1853);
				builder.setView(nicknameField);
				builder.setPositiveButton(R.string.btnConfirmar, new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						String nickname=((EditText)mDialog.findViewById(1853)).getText().toString();
						new Thread(PresenceThread.getInstance(myAndroidId, nickname)).start();
					}
				});
				mDialog = builder.create();
				mDialog.show();
				break;

			default:
				Toast.makeText(this, "Função não implementada ainda!", Toast.LENGTH_LONG).show();
				break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater mInflater = getMenuInflater();
        mInflater.inflate(R.menu.main_menu, menu);
        return true;
	}

}
